package com.yl.common.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Locale;

/**
 * create by cjx on 2024/12/9
 * desc: 获取网络状态
 */
public class NetUtil {
    @SuppressLint("MissingPermission")
    public static String getIpAddress(Context context) {
        ConnectivityManager netManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = netManager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            // wifi
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                return String.format(Locale.CHINA, "%d.%d.%d.%d", ipAddress & 0xFF, ipAddress >> 8 & 0xFF, ipAddress >> 16 & 0xFF, ipAddress >> 24 & 0xFF);
            } else {
                final String interfaceName = "eth0";
                try {
                    Enumeration<NetworkInterface> netInterface = NetworkInterface.getNetworkInterfaces();
                    while (netInterface.hasMoreElements()) {
                        NetworkInterface network = netInterface.nextElement();
                        if (!network.isUp()) {
                            continue;
                        }
                        if (!interfaceName.equals(network.getDisplayName())) {
                            continue;
                        }
                        Enumeration<InetAddress> addressList = network.getInetAddresses();
                        while (addressList.hasMoreElements()) {
                            InetAddress inetAddress = addressList.nextElement();
                            if (inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (Exception ignore) {

                }
            }
        }
        return null;
    }
}
